import { Injectable,forwardRef,Inject } from '@nestjs/common';
import { CreateVirtualNodeDto } from './dto/create-virtual-node.dto';
import { UpdateVirtualNodeDto } from './dto/update-virtual-node.dto';
import { NodeService } from 'src/node/node.service';
import { ResponseUtil } from 'src/common/utils/response.util';
import { WebsocketGateway} from '../websocket/websocket.gateway';
@Injectable()
export class VirtualNodeService {   
    constructor(
        @Inject(forwardRef(()=>NodeService)) private nodeService:NodeService,
        @Inject(forwardRef(()=>WebsocketGateway)) private websocketGateway:WebsocketGateway
    ){}


   //添加虚拟节点
   addVirtualNode(body:any){
    const connectionStatusTypes = [0, 1]; // 0:未连接 1:已连接
    const randomTypeIndex = Math.floor(Math.random() * connectionStatusTypes.length);
    const connectionStatus = connectionStatusTypes[randomTypeIndex];
    const newNode:any = {
        connectionStatus: connectionStatus, //0:未连接 1:已连接
        createdBy: "",
        createdTime: new Date().getTime(),
        id: this.nodeService.deployedNodes.length,
        ipAddress: `192.168.${this.nodeService.deployedNodes.length+1}.${this.nodeService.deployedNodes.length+1}`,
        nodeId: this.nodeService.deployedNodes.length,
        type:0, 
        updatedBy: "",
        updatedTime: new Date().getTime(),
    }
    this.nodeService.deployedNodes.push(newNode)
    const { nodeId} = body
    const cmd = "JRLC.run.in.container.app"
    this.websocketGateway.createStatus([nodeId],cmd)
    return ResponseUtil.success(newNode,"添加虚拟节点成功")
   }


  //获取虚拟节点列表
  getVirtualNodeList(body:any){
    const {currentPage,pageSize} = body
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const records = this.nodeService.deployedNodes.filter(item=>item.type==0).slice(startIndex,endIndex)
    const total = this.nodeService.deployedNodes.filter(item=>item.type==0).length
    const  data = {
      records:records,
      total:total
    }
    return ResponseUtil.success(data,"获取虚拟节点列表成功")
  }

  //获取虚拟节点数量
  getVirtualNodeNum(body:any){
    return ResponseUtil.success(2,"获取虚拟节点数量成功")
  }


  // 一键启动虚拟节点
  startVirtualNode(body:any){
    const {ips} = body
    const cmd = "JRLC.start.in.container.app"
    this.websocketGateway.createStatus(ips,cmd)
    return ResponseUtil.success(2,"一键启动虚拟节点成功")
  }

  // 一键停止虚拟节点
  stopVirtualNode(body:any){
    const {ips} = body
    const cmd = "JRLC.stop.in.container.app"
    this.websocketGateway.createStatus(ips,cmd)
    return ResponseUtil.success(2,"一键停止虚拟节点成功")
  }

  // 一键删除虚拟节点
  deleteVirtualNode(body:any){
    const {ips} = body
    const cmd = "JRLC.delete.in.container.app"
    this.websocketGateway.createStatus(ips,cmd)
    return ResponseUtil.success(2,"一键删除虚拟节点成功")
  }
  


  

  
  
  
}

